import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import java.text.DateFormat
import java.text.SimpleDateFormat

class ChemicalSimilarityMapController {

  //needed for url generation
  def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib()
  ChemSimilarityUtil chemSimilarityUtil = new ChemSimilarityUtil()

  ChemSimilarityService chemSimilarityService



  def index = {

    if( params.txtProbabilityFactor != null )
    {
        flash.message = ""
        println "============ Comming into submit mathod of ChemicalSimilarityMapController ================\n"
        println "parmas.txtProbabilityFactor :: ${params.txtProbabilityFactor}"
        println "parmas.txtCSVData :: ${params.txtCSVData}"
        println "parmas.filePath :: ${params.filePath}"
        println "parmas.filePath.getClass :: ${params.filePath?.getClass()}"

        if(request instanceof MultipartHttpServletRequest)
        {
          MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
          CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("filePath");

          println "Type : ${f.contentType}"
          println "Name : ${f.getName()}"


          if(f.empty && (params.txtCSVData==null || params.txtCSVData.toString().trim().length() == 0 ) )
          {
            flash.message = "Error! Data is mandatory."
            redirect(action:"index")
          }else
          if( !f.contentType.toString().equalsIgnoreCase("text/plain") && !f.contentType.toString().equalsIgnoreCase("text/csv"))
          {
            flash.message = "Error! Bad extension, Upload only .csv or .txt extension file."
            redirect(action:"index")
          }else
          if( params.txtProbabilityFactor == null || params.txtProbabilityFactor.toString().trim().length() == 0 )
          {
            flash.message = "Error! ProbabilityFactor is mandatory."
            redirect(action:"index")
          }else
          {
           try
            {
              if( Double.parseDouble(params.txtProbabilityFactor) < 0.01 || Double.parseDouble(params.txtProbabilityFactor) > 1.0 )
              {
                  flash.message = "Error! Please enter Probability Factor between the range of 0.01 to 1.0"
                  redirect(action:"index")
              }
            }catch(NumberFormatException e)
            {
                flash.message = "Error! Enter valid Probability Factor."
                redirect(action:"index")
            }
          }

          String inputStr = "";
          if(!f.empty)
          {
            DataInputStream in1 = new DataInputStream(f.getInputStream());

            while (in1.available() !=0)
            {
              if(inputStr.length() == 0)
              {
                inputStr += in1.readLine();
              }else
              {
                inputStr += "\n"+in1.readLine();
              }
            }
            in1.close();
          }
          else
          {
            inputStr = params.txtCSVData.toString();
          }

          println "inputStr : ${inputStr}";




          ArrayList<String> res = chemSimilarityUtil.getMappingFromText(inputStr);
          println "res :: ${res}"
          println "f.getOriginalFilename() :: ${f.getOriginalFilename()}"

          String filePath = chemSimilarityService.createOutputFile(res,f.getOriginalFilename());

          println("filePath :: "+filePath)

          return ["Result":res,"filePath":filePath]

        }
        else
        {
          println 'request is not of type MultipartHttpServletRequest'
        }
    }
    return [:]
  }

//  private String getOutPutFile(ArrayList data,String fileName)
//  {
//      // Used for folder creation : Start
//      DateFormat dateFormat = new SimpleDateFormat ("MMddyyyy");
//      java.util.Date date = new java.util.Date ();
//      String dateStr = dateFormat.format (date);
//
//	  // Used for File Creation
//	  dateFormat = new SimpleDateFormat ("HHmmss");
//	  dateStr = dateStr + "_" +dateFormat.format (date);
//
//      fileName = fileName+"_"+dateStr+".sif";
//      //String filesFullPath = g.createLinkTo(dir: 'outputFiles',file : fileName)
//
//      //println "filesFullPath : ${filesFullPath}"
//
//      //chemSimilarityUtil.createOutputFile(data,filesFullPath)
//
//
//    File imageDir = AppContext.getApplicationContext().getResource("outputFiles/").getFile()
//    String mainDir = "/" + imageDir.getName()
////    imageDir = new File(imageDir, "compounds")
////    mainDir = mainDir + "/" + imageDir.getName()
////    if (!imageDir.exists()) {
////      imageDir.mkdirs()
////    }
//
//
//    //String name = "${fileName}-${size}-${color}.png"
//    String finalName = g.createLinkTo(dir: mainDir, file: fileName)
//    println "finalName : ${finalName}"
//
//
//    File f = new File(imageDir, name);
//
//
//
//
//
//
//      return finalName;
//  }


}
